<template>
  <div
    style="
            background-color: rgba(248, 249, 249, 1);
            height: 120px;
            padding-left: 20px;
            margin: 20px 0;
            display: flex;
        "
  >
    <div v-show="!showProgress" style="width: 100%; display: flex; align-items: center; position: relative">
      <Upload
        ref="uploadRef"
        style="width: 340px"
        action="/"
        :before-upload="handleUpload"
        :max-size="51200"
        :show-upload-list="false"
        :format="format"
        type="drag"
      >
        <!--            <Button icon="ios-cloud-upload-outline">Select the file to upload</Button> -->
        <Input
          placeholder="请选择需要导入的文件"
          suffix="ios-folder-outline"
          readonly
          :value="file ? file.name : ''"
        />
      </Upload>
      <div style="margin-left: 10px">
        支持xlsx文件，单个文件不得大于1M
      </div>
      <div v-if="errorMsg" style="color: red; position: absolute; bottom: 20px">
        {{ errorMsg }}
      </div>
    </div>
    <div
      v-show="showSheet"
      id="luckysheet"
      style="
                margin: 0px;
                padding: 0px;
                position: absolute;
                width: 100%;
                height: 80%;
                left: 0px;
                top: 120px;
                display: none;
            "
    />
    <div
      v-show="showProgress"
      style="
                width: 100%;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: space-around;
            "
    >
      <span>正在导入数据，请勿关闭页面</span>
      <Progress :percent="percent" :stroke-width="20" :stroke-color="['#108ee9', '#87d068']" status="active" />
    </div>
  </div>
</template>

<script>
import LuckyExcel from 'luckyexcel'

export default {
  name: 'UploadExcel',
  props: {
    headerLength: {
      type: Number,
      default: 16
    },
    isValidTemptate: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      errorMsg: '',
      showProgress: false,
      percent: 10,
      file: null,
      format: ['xlsx'],
      showSheet: false,
      changeExcelOption: {
        container: 'luckysheet',
        showtoolbar: false,
        showsheetbar: false, // 是否显示底部sheet页按钮
        allowCopy: true,
        userInfo: true,
        hook: {
          // 狗子函数
          cellUpdateBefore (r, c, v, f) {
            // 监听单元格修改之前
            // eslint-disable-next-line no-undef
            if (r < thisLockRow) { return false }

            return true
          }
        }
      },
      interval: null
    }
  },
  mounted () {
    this.init()
  },
  // watch: {
  //     percent(val) {
  //         console.log('percent', val)
  //     }
  // },
  methods: {
    clear () {
      this.file = null
      this.errorMsg = ''
      this.$refs.uploadRef.clearFiles()
    },
    init () {
      this.percent = 10
      this.showProgress = false
      this.file = null
      this.errorMsg = ''
    },
    handleUpload (file) {
      this.file = file
      this.errorMsg = ''
      let check = true
      if (file.size > 1024 * 1024) {
        this.errorMsg += '请上传1MB以内的xlsx文件\n'
        check = false
      }
      // let type = file.name.substring(file.name.indexOf('.') + 1)
      const parts = file.name.split('.')
      const type = parts[parts.length - 1]
      if (!this.format.includes(type)) {
        this.errorMsg += `【${file.name}】文件格式不支持，当前只支持【${this.format}】格式\n`
        check = false
      }
      if (!this.isValidTemptate) {
        this.$emit('checkExcel', check)
        return
      }
      LuckyExcel.transformExcelToLucky(file, (exportJson, luckysheetfile) => {
        if (exportJson.sheets === null || exportJson.sheets.length === 0) {
          this.$Message.error('无法读取excel文件的内容，当前不支持xls文件！')
          return
        }
        window.luckysheet.destroy()
        this.changeExcelOption.data = exportJson.sheets
        this.changeExcelOption.title = file.name.substring(0, file.name.indexOf('.xlsx'))
        window.luckysheet.create(this.changeExcelOption)
        if (!this.checkHeader(exportJson.sheets[0].data)) {
          this.errorMsg += '导入的表格，与模板不匹配。请下载模板，重新编辑上传；\n'
          check = false
        }
        this.$emit('checkExcel', check)
      })
      return false
    },
    checkHeader (data) {
      const row = data[0]
      let i
      for (i = 0; i < row.length; i++) {
        if (!row[i]) { break }
      }
      console.log(i, this.headerLength)
      return i === this.headerLength
    },
    getFile () {
      this.showProgress = true
      return this.file
    },
    autoAddProgress () {
      clearInterval(this.interval)
      this.interval = setInterval(() => {
        const random = Math.floor(Math.random() * 20)
        if (random + this.percent > 100) {
          this.percent = 100
          clearInterval(this.interval)
        } else {
          this.percent += random
        }
      }, 300)
    },
    finish () {
      this.percent = 100
    },
    checkFile () {
      if (this.file) { return true }

      return false
    }
  }
}
</script>

<style scoped>
</style>
